package org.example.microservice.common.utils;

import java.util.Arrays;

public class SequenceUtil {

    private static final String ranges = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    /**
     * 文档请参考：{@link SequenceUtil#nextval(String, String, int)}
     */
    public static String nextval(String currval, int length) {
        return nextval(ranges, currval, length);
    }

    /**
     * 在指定的序列范围内，获取当前序列的下一个序列的值。<p />
     * 例如，序列范围=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ，当前序列值=39Z，那么：下一序列值=3A0
     *
     * @param range   序列范围（序列范围中的字符不能重复）
     * @param currval 当前序列值（当前序列值中的字符必须在序列范围内）
     * @param length  序列长度（序列长度必须和当前序列值的长度一致）
     * @return 下一序列值（如果超出范围，会抛出异常）
     */
    public static String nextval(String range, String currval, int length) {
        if (currval == null || "".equals(currval)) {
            char[] values = new char[length];
            Arrays.fill(values, range.charAt(0));
            return String.valueOf(values);
        }

        if (currval.length() != length) {
            throw new RuntimeException("序列长度和当前序列值的长度不一致，无法创建");
        }

        char[] lasts = new char[length];
        Arrays.fill(lasts, range.charAt(range.length() - 1));
        if (currval.equals(String.valueOf(lasts))) {
            throw new RuntimeException("序列已超过最大值，无法创建");
        }

        char[] characters = currval.toCharArray();
        int i = characters.length - 1;
        while (true) {
            if (i < 0) {
                break;
            }
            if (characters[i] == range.charAt(range.length() - 1)) {
                characters[i] = range.charAt(0);
                i = i - 1;
            } else {
                characters[i] = range.charAt(range.indexOf(characters[i]) + 1);
                break;
            }
        }
        return String.valueOf(characters);
    }
}
